<template>
  <!-- 手机密码登录 -->
  <div class="phone">
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginFormRef"
      label-width="100px"
      label-position="top"
      hide-required-asterisk
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="loginForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <div class="btn">
        <el-button type="primary" @click="doLogin">提交</el-button>
        <el-button @click="resetForm('loginFormRef')">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { login } from '../../api/login.js'
import md5 from 'js-md5'
export default {
  data () {
    // 验证规则定义
    // 手机号验证
    const checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    // 密码验证
    const checkPassword = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        phone: '',
        password: '',
        md5_password: ''
      },
      // 验证规则
      rules: {
        phone: [
          // { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        // 名字要和v-model绑定的表单的属性名对应不然报错please pass correct props!
        password: [
          { validator: checkPassword, trigger: 'blur' }
        ]
      }
    }
  },
  props: [],
  methods: {
    // 重置表单
    resetForm (formRef) {
      this.$refs[formRef].resetFields()
    },
    // 执行登录
    doLogin () {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请输入正确信息')
        // 转为md5
        this.loginForm.md5Password = md5(this.loginForm.password)
        const res = await login(this.loginForm)
        if (res.data.code !== 200) return this.$message.error(`登录失败${res.data.$message}`)
        this.$message.success('登录成功')
        this.$store.commit('saveUserInfo', res.data)
        this.$store.commit('setIsLogin', true)
        this.$router.push('/personalRecom')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.phone {
  display: flex;
  flex-direction: column;
}
.el-form-item {
  text-align: left;
}
.btn {
  text-align: left;
}
</style>
